﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace Citi.Scheduler.WindowsServices
{
    public static class LogUtil
    {
        public static string PathLogErro { get; set; }

        public static void LogError(EventLog eventLog, string message)
        {
            Log(eventLog, message, EventLogEntryType.Error);
        }

        public static void LogError(EventLog eventLog, Exception exception)
        {
            Log(eventLog, GetAllExceptionDetails(exception), EventLogEntryType.Error);
        }

        public static void Log(EventLog eventLog, string message, EventLogEntryType logType)
        {
            try
            {
                eventLog.WriteEntry(message, logType);
                Console.WriteLine(message);
            }
            catch { }

            try
            {
                File.AppendAllLines(PathLogErro,
                    new List<string> { string.Format("{0} - {1}: {2}", eventLog.Source, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), message), string.Empty });
            }
            catch { }
        }

        public static string GetAllExceptionDetails(Exception e)
        {
            var errorDescriptionMessage = string.Empty;

            while (e != null)
            {
                errorDescriptionMessage += string.Format("\n Error: {0}. \n Inner Exception: {1}. \n Stack Trace: {2}",
                    e.Message, e.InnerException != null ? e.InnerException.Message : "No data", string.IsNullOrEmpty(e.StackTrace) ? "No data" : e.StackTrace);
                e = e.InnerException;
            }

            return errorDescriptionMessage;
        }
    }
}
